package com.hkts.naturalgasauthentication.security.validate;


import com.hkts.naturalgasauthentication.common.Exception.CodeIsErrorException;
import com.hkts.naturalgasauthentication.common.Exception.CodeIsNullException;
import com.hkts.naturalgasauthentication.security.jwt.AuthenticationFailHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Configuration
public class MobileValidateFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationFailHandler authenticationFailHandler;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1. 判断 请求是否为手机登录，且post请求
        if("/authentication/mobile/login".equals(request.getRequestURI())
                && "post".equalsIgnoreCase(request.getMethod())) {
            try {
                // 校验验证码合法性
                validate(request);
            }catch (AuthenticationException e) {
                // 交给失败处理器进行处理异常
                authenticationFailHandler.onAuthenticationFailure(request, response, e);
                // 一定要记得结束
                return;
            }
        }

        // 放行
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        // 先获取seesion中的验证码
        String sessionCode =redisTemplate.opsForValue().get(request.getParameter("mobile"));
        if(sessionCode==null){
            throw  new CodeIsNullException("该手机未发验证码！");
        }
        // 获取用户输入的验证码
        String inpuCode = request.getParameter("code");
        // 判断是否正确
        if(!sessionCode.equals(inpuCode)){
            throw  new CodeIsErrorException("验证码错误！");
        }

    }
}
